package com.ly.drivingschool.controller;

import com.ly.drivingschool.common.ResponseMessage;
import com.ly.drivingschool.dao.OrderDao;
import com.ly.drivingschool.dao.UserDao;
import com.ly.drivingschool.pojo.*;
import com.ly.drivingschool.service.DictService;
import com.ly.drivingschool.service.OrderService;
import com.ly.drivingschool.service.SetmealService;
import com.ly.drivingschool.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 订单(报名信息)管理
 */
@Slf4j
@RestController
@RequestMapping(value = "order",produces = "application/json; charset=utf-8")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SetmealService setmealService;

    /**
     * 分页查询驾校订单信息
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "getPageOrderInfo")
    public ResponseMessage getPageOrderInfo(int page, int limit) {
        Pager<OrderPage> pager = orderService.findByPager(page,limit);
        System.out.println(pager);
        if (pager.getCount() == 0) {
            return ResponseMessage.createBySuccess("暂无订单信息",pager);
        } else {
            return ResponseMessage.createBySuccess(pager);
        }
    }

    /**
     * 模糊查询
     * @param page
     * @param limit
     * @param keyWork
     * @return
     */
    @GetMapping(value = "getKeyWorkOrderInfo")
    public ResponseMessage getKeyWorkOrderInfo(int page,int limit, String keyWork){
        Pager<OrderPage> pager = orderService.findByKey(page,limit,keyWork);
        if (pager.getCount() == 0) {
            return ResponseMessage.createBySuccess("没有该订单信息,请检查",pager);
        } else {
            return ResponseMessage.createBySuccess(pager);
        }
    }

    /**
     * 选择条件查询
     * @param page
     * @param limit
     * @param col
     * @param code
     * @return
     */
    @GetMapping(value = "findByCondition")
    public ResponseMessage findByCondition(int page, int limit,String col,String code){
        Pager<OrderPage> pager = orderService.findByCondition(page,limit,col,code);
        System.out.println(pager);
        if (pager.getCount() == 0) {
            return ResponseMessage.createBySuccess("无该人员信息,请检查",pager);
        } else {
            return ResponseMessage.createBySuccess(pager);
        }
    }

    /**
     * 查看订单信息
     * @param order_id
     * @return
     */
    @GetMapping(value = "getByIdOrder")
    public ResponseMessage getByIdOrder(int order_id) {
        OrderPage student = orderService.selectByPrimaryKey(order_id);
        System.out.println("订单信息：" + student);
        if (student == null) {
            return ResponseMessage.createByErrorMessage("没有该订单信息");
        } else {
            return ResponseMessage.createBySuccess("查看订单信息",student);
        }
    }

    /**
     * 更新记录
     * @param order
     * @return
     */
    @PostMapping(value = "updateByIdOrder")
    public ResponseMessage updateByIdOrder(@RequestBody Order order){
        System.out.println("获取的Order信息：" + order.toString());
        int code = orderService.updateByPrimaryKeySelective(order);
        if (code == 0) {
            return ResponseMessage.createByErrorMessage("更新失败");
        } else {
            return ResponseMessage.createBySuccess("更新成功", code);
        }
    }

    /**
     * 查询添加订单的个人信息以及模板信息
     * @param idCard
     * @return
     */
    @GetMapping(value = "tmlData")
    public ResponseMessage tmlData(String idCard) {
        // 查询没有订单的用户个人信息
        User user = userService.selectByIdCard(idCard);
        // 查询字典值 报名状态
        List<Dict> dictList = dictService.getByBelong("bm001");
        // 查询套餐信息
        List<Setmeal> setmealList = setmealService.getAllSetmeal();

        if (user == null) {
            return ResponseMessage.createByErrorMessage("找不到该学员信息或者该学员已有订单，请先注册");
        } else {
            // 封装信息
            HashMap<String,Object> dataMap = new HashMap<String,Object>();
            dataMap.put("userInfo",user);
            dataMap.put("dictList",dictList);
            dataMap.put("setmealList",setmealList);

            return ResponseMessage.createBySuccess("新增新的订单",dataMap);
        }
    }

    /**
     * 后台管理员_添加新的订单
     * @param order
     * @return
     */
    @PostMapping(value = "addOrderInfo")
    public ResponseMessage addOrderInfo(@RequestBody Order order) {
        System.out.println("获取的数据：" + order.toString());

        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String createTime = df.format(calendar.getTime());

        // 封装数据
        order.setCreatetime(createTime);// 创建时间
        order.setValidtime(createTime + "-" + order.getValidtime());// 有效时间
        order.setOrderunpaid(order.getOrdertotal()-order.getOrderpaid());// 待付金额
        order.setDd001("019");// 订单状态_已生效

        int code = orderService.insertSelective(order);
        if (code == 1) {
            // 成功添加一条记录 更改用户表状态xy001 = 007
            User user = new User();
            user.setXy001("007");
            user.setUser_id(order.getUser_id());
            userService.updateByPrimaryKeySelective(user);

            return ResponseMessage.createBySuccess("添加订单成功，用户状态成功更改");
        } else {
            return ResponseMessage.createByErrorMessage("添加订单失败，请联系管理员");
        }
    }

    // 校验是否已经存在订单 根据openId判断
    // 未存在订单则返回用户信息并且调用添加订单接口
    @GetMapping(value = "checkOrder")
    public ResponseMessage checkOrder(String open_id,int setmeal_id,double actPrice) {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        String createTime = df.format(calendar.getTime());

        calendar.set(Calendar.YEAR,calendar.get(Calendar.YEAR)+1);
        String validtime = df.format(calendar.getTime());

        User user = userDao.selectByOpenId(open_id);
        System.out.println(user);
        if (user == null) {
            // 不存在该学员，请先登记
            return ResponseMessage.createByErrorMessage("请先登记为学员");
        } else {
            // 存在该学员 判断是否存在订单
            Order order = orderDao.getOrderByUserId(user.getUser_id());
            System.out.println(order);
            // 判断订单是否存在 存在则继续
            if (order == null) {
                // 订单不存在可以进行订单信息添加
                System.out.println("添加订单");
                Order newOrder = new Order();
                newOrder.setSetmealId(setmeal_id);
                newOrder.setOrdertotal(actPrice);
                newOrder.setOrderpaid(actPrice);
                newOrder.setOrderadvance(0.00);
                newOrder.setOrderunpaid(0.00);
                newOrder.setBm001("014");
                newOrder.setDd001("019");
                newOrder.setUser_id(user.getUser_id());
                newOrder.setValidtime(createTime + "-" + validtime);
                newOrder.setCreatetime(createTime);

                int code = orderService.insertSelective(newOrder);

                if (code == 1) {
                    // 成功添加一条记录 更改用户表状态xy001 = 007
                    User user1 = new User();
                    user1.setXy001("007");
                    user1.setUser_id(newOrder.getUser_id());
                    userService.updateByPrimaryKeySelective(user1);

                    return ResponseMessage.createBySuccess("购买成功，用户状态成功更改");
                } else {
                    return ResponseMessage.createByErrorMessage("添加订单失败，请联系管理员");
                }
            } else {
                System.out.println("已经存在订单");
                return ResponseMessage.createByErrorMessage("已经存在订单");
            }
        }
    }

}
